package com.huchao.www.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.huchao.www.factory.SpringJobFactory;
import lombok.SneakyThrows;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Description:
 * @BelongsProject: background-management-v10
 * @BelongsPackage: com.huchao.www.config
 * @Author: 亖思
 * @CreateTime: 2023/3/20 10:30
 * @Version: 1.0
 */
@Configuration
public class QuartzConfig {
    @Resource
    private SpringJobFactory springJobFactory;

    public QuartzConfig(SpringJobFactory springJobFactory){
        this.springJobFactory = springJobFactory;
    }

    /**
     * 〈通过SchedulerFactoryBean获取Scheduler的实例〉
     *
     * @Author: 亖思
     * @Date: 2023/3/20 10:43
     * @return: org.quartz.Scheduler
     **/
    @SneakyThrows
    @Bean(name = "scheduler")
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }


    /**
     * 〈quartz初始化监听器 这个监听器可以监听到工程的启动，在工程停止再启动时可以让已有的定时任务继续进行。〉
     *
     * @Author: 亖思
     * @Date: 2023/3/20 11:08
     * @return: org.quartz.ee.servlet.QuartzInitializerListener
     **/
//    public QuartzInitializerListener executorListener() {
//        return new QuartzInitializerListener();
//    }


    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 设置properties配置文件
        //factory.setQuartzProperties(propertiesFactoryBean.getObject());
        // 支持在JOB实例中注入其他的业务对象
        factory.setJobFactory(springJobFactory);
        // 设置延迟时间:项目启动完成后，等待0秒后开始执行调度器初始化 默认0
        factory.setStartupDelay(10);
        // 这样当spring关闭时，会等待所有已经启动的quartz job结束后spring才能完全shutdown
        factory.setWaitForJobsToCompleteOnShutdown(true);

        factory.setApplicationContextSchedulerContextKey("application");

        return factory;
    }
}
